﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using SaleManagement.Web.App_Code;
using SaleManagement.Domains;
using SaleManagement.Services;
using System.Transactions;

namespace SaleManagement.Web.Pages
{
  public partial class ImportInfo : BasePage
  {
    #region Variables and properties
    private string _InnerError = string.Empty;

    private DataTable ImportDetailTable
    {
      get
      {
        if (Session["ImportDetailTable"] == null)
        {
          DataTable dt = new DataTable();
          Session["ImportDetailTable"] = dt;
        }
        return Session["ImportDetailTable"] as DataTable;
      }

      set
      {
        Session["ImportDetailTable"] = value;
      }
    }

    private int DetailId
    {
      get
      {
        if (Session["ImportDetailId"] == null)
        {
          Session["ImportDetailId"] = 0;
        }

        return Convert.ToInt32(Session["ImportDetailId"]);
      }

      set
      {


        Session["ImportDetailId"] = value;
      }
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack && !IsCallback)
      {
        if (!string.IsNullOrEmpty(Request.QueryString["id"]))
        {
          hfImportId.Value = Request.QueryString["id"];
        }

        LoadCommonInfo();
        LoadImportDetailList();
      }
    }

    protected void cbxProduct_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
      cbxProduct.DataSource = new ProductService().GetByGroupId(Convert.ToInt32(cbxProductGroup.Value));
      cbxProduct.DataBind();
    }

    protected void gvImportDetail_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
      string[] para = e.Parameters.Split('|');
      switch (para[0])
      {
        case "DeleteDetail":
          _InnerError = DeleteImportDetail(Convert.ToInt32(para[1]));
          break;
        case "SaveDetail":
          _InnerError = SaveImportDetail();
          break;
        case "Save":
          _InnerError = Save();
          break;
        default:
          break;
      }

      LoadImportDetailList();
    }

    protected void gvImportDetail_CustomJSProperties(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = _InnerError;
    }

    protected void gvImportDetail_PageIndexChanged(object sender, EventArgs e)
    {
      LoadImportDetailList();
    }
    #endregion

    #region Methods
    private void LoadCommonInfo()
    {
      int importId;
      if (int.TryParse(hfImportId.Value, out importId))
      {
        #region Import
        Import import = new ImportService().GetById(importId);
        if (import != null)
        {
          txtRefNo.Text = import.RefNo;
          deImportDate.Date = import.ImportDate;
          cbxRepository.Value = import.RepositoryId;
          txtTotalAmount.Value = import.TotalAmount;
          mmNote.Text = import.Notes;
        }
        #endregion
      }

      #region ImportDetail
      DataSet ds = new ImportDetailService().SearchByImportId(importId);
      if (ds != null && ds.Tables.Count > 0)
      {
        ImportDetailTable = ds.Tables[0];
        ImportDetailTable.PrimaryKey = new DataColumn[] { ImportDetailTable.Columns["Id"] };
        ImportDetailTable.Columns.Add("Deleted", typeof(bool));
      }
      #endregion

      #region Combobox
      cbxProductGroup.DataSource = new ProductGroupService().GetAll();
      cbxProductGroup.DataBind();

      cbxRepository.DataSource = new RepositoryService().Search(StatusList.RepositoryType.PRODUCT);
      cbxRepository.DataBind();
      #endregion
    }

    private void LoadImportDetailList()
    {
      gvImportDetail.DataSource = ImportDetailTable;
      gvImportDetail.FilterExpression = "Deleted <> true";
      gvImportDetail.DataBind();
    }

    private string SaveImportDetail()
    {
      try
      {
        int detailId;
        DataRow row = null;
        if (int.TryParse(hfDetailId.Value, out detailId))
        {
          row = ImportDetailTable.Rows.Find(detailId);
        }

        if (row == null)
        {
          row = ImportDetailTable.NewRow();
          row["Id"] = DetailId;
          DetailId -= 1;
          ImportDetailTable.Rows.Add(row);
        }

        row["ProductGroupId"] = cbxProductGroup.Value;
        row["ProductGroupName"] = cbxProductGroup.Text;
        row["ProductId"] = cbxProduct.Value;
        row["ProductName"] = cbxProduct.Text;
        row["Quantity"] = Convert.ToInt32(txtQuantity.Value);
        row["Deleted"] = false;

        return "SaveDetail";
      }
      catch (Exception ex)
      {
        WriteLog("ImportInfo::SaveImportDetail", ex);
        return "Có lỗi trong quá trình lưu dữ liệu";
      }
    }

    private string DeleteImportDetail(int id)
    {
      try
      {
        DataRow row = ImportDetailTable.Rows.Find(id);
        if (row != null)
        {
          row["Deleted"] = true;
        }

        return "DeleteDetail";
      }
      catch (Exception ex)
      {
        WriteLog("ImportInfo::DeletePurchaseImportDetai", ex);
        return "Có lỗi trong quá trình xóa dữ liệu";
      }
    }

    private string Save()
    {
      try
      {
        Import import = null;
        ImportService importService = new ImportService();

        using (TransactionScope scope = new TransactionScope())
        {
          int importId;
          ImportDetailService detailService = new ImportDetailService();
          ProductService productService = new ProductService();

          #region Import
          if (int.TryParse(hfImportId.Value, out importId))
          {
            import = importService.GetById(importId);
          }

          if (import == null)
          {
            import = new Import();
          }

          import.ImportDate = deImportDate.Date;
          import.RepositoryId = Convert.ToInt32(cbxRepository.Value);
          import.TotalAmount = Convert.ToInt32(txtTotalAmount.Text);
          import.UpdatedBy = CurrentUser.Username;
          import.UpdatedDate = DateTime.Now;
          import.Notes = mmNote.Text;

          importService.Save(import);
          #endregion

          #region Detail
          foreach (DataRow row in ImportDetailTable.Rows)
          {
            int detailId = Convert.ToInt32(row["Id"]);
            bool deleted = row["Deleted"] == DBNull.Value ? false : Convert.ToBoolean(row["Deleted"]);
            ImportDetail detail = null;
            if (detailId > 0)
            {
              detail = detailService.GetById(detailId);
            }

            if (deleted)
            {
              #region Delete
              if (detail != null)
              {
                detailService.Delete(detail);
              }
              #endregion
            }
            else
            {
              #region Save
              if (detail == null)
              {
                detail = new ImportDetail();
              }

              detail.ImportId = import.Id;
              detail.ProductId = Convert.ToInt32(row["ProductId"]);
              detail.Quantity = Convert.ToInt32(row["Quantity"]);

              detailService.Save(detail);
              row["Id"] = detail.Id;
              #endregion
            }
          }
          #endregion

          scope.Complete();
        }

        import = importService.GetById(import.Id);
        return string.Format("Save|{0}|{1}", import.Id.ToString(), import.RefNo);
      }
      catch (Exception ex)
      {
        WriteLog("InportInfo::SaveImport", ex);
        return "Có lỗi trong quá trình lưu dữ liệu";
      }
    }
    #endregion
  }
}
